<?php
namespace App\Controller;

class UserController extends BaseController
{
    public function login()
    {
        $this->display();
    }

    public function register()
    {
        $this->display();
    }

    public function contact()
    {
        $contact = D("Contact")->getContactList(array("user_id" => session("userId")));
        $this->assign("contact", $contact);
        $this->display();
    }

    public function addContact()
    {
        if (IS_POST) {
            $data = I("post.");
            $data["user_id"] = session("userId");
            D("Contact")->addContact($data);
            $this->redirect("App/User/contact");
        } else {
            if (I("get.id")) {
                $contact = D("Contact")->getContact(array("id" => I("get.id")));
                $this->assign("contact", $contact);
            }

            $this->display();
        }
    }

    public function delContact()
    {
        D("Contact")->delContact(I("get.id"));
        $this->redirect("App/User/contact");
    }

    public function selectContactJson()
    {
        D("User")->updateUser(session("userId"), array("contact_id" => I("get.id")));
    }

    public function loginJson()
    {
        $condition["phone"] = I("post.phone");
        $condition["password"] = md5(I("post.password"));
        $user = D("User")->getUser($condition);
        if ($user && $user["status"]) {
            session("userName", $user["username"]);
            session("userId", $user["id"]);
            session("userOpenId", $user["openid"]);

            //reset token
            $token = getRandom(32);
            D("User")->updateUser($user["id"], array("token" => $token));

            $this->ajaxReturn($user);
        }
    }

    public function registerJson()
    {
        $data ["openid"] = "appOpenId_" . date("ymdhis") . mt_rand(100, 999);
        $data ["username"] = I("post.username");
        $data ["phone"] = I("post.phone");
        $data ["password"] = md5(I("post.password"));
        $data ["status"] = 1;
        $user = D("User")->getUserCondition(array("phone" => I("post.phone")));
        if ($user) {
            $this->ajaxReturn(array("info" => "注册失败"));
            return;
        }

        D("User")->addUser($data);
        $this->ajaxReturn(array("info" => "注册成功"));
    }

    public function oauthDebug()
    {


            session("userOpenId", "oojFxs4s3PSZVjL-X5UpFPhNfG0c");
            session("userName", "John");
            session("userId", 2);

    }

    public function oauthLogin()
    {
        $this->oauthDebug();

        if (!session("userId")) {
            $config = D("Config")->getConfig();
            if ($config["oauth"]) {
                $weObj = D("WxConfig")->getWeObj();
                $token = $weObj->getOauthAccessToken();
                if (!$token) {
                    $url = $weObj->getOauthRedirect($this->appUrl . __SELF__);
                    header("location: $url");
                    return;
                } else {
                    $userInfo = $weObj->getOauthUserinfo($token["access_token"], $token["openid"]);
                    $this->oauthRegister($userInfo);
                }
            }
        }

        $user = D("User")->getUser(array("id" => session("userId")), true);
        if ($user["status"] == 0) {
            $this->redirect("Empty/index");
            return;
        }
        $user = json_encode($user);
        $this->assign("user", $user);
    }

    public function oauthRegister($userInfo)
    {
        $user = D("User")->getUser(array("openid" => $userInfo["openid"]));
        $data = array(
            "username" => $userInfo["nickname"],
            "subscribe" => 1,
            "sex" => $userInfo["sex"],
            "language" => $userInfo["language"],
            "city" => $userInfo["city"],
            "province" => $userInfo["province"],
            "avater" => $userInfo["headimgurl"],
        );

        $userId = 0;
        if ($user) {
            $userId = $user["id"];
            D("User")->updateUser($userId, $data);
        } else {
            $data["openid"] = $userInfo["openid"];
            $userId = D("User")->addUser($data);
        }

        session("userId", $userId);
        session("userOpenId", $userInfo["openid"]);
    }

    public function isLoginJson()
    {
        $isLogin = $this->is_login();
        if (!$isLogin) {
            $this->ajaxReturn(array("info" => "未登陆", "code" => 0));
        }
    }

    public function getUserJson()
    {
        $this->isLoginJson();

        $user = D("User")->getUser(array("id" => session("userId")), true);
        if (I("get.getOrder")) {
            $user["order"] = D("Order")->getOrderList(array("user_id" => session("userId"), "status" => array("gt", -1)), true);
        }

        if (I("get.getProvince")) {
            $user["province"] = D("LocProvince")->getProvinceList(array(), true);
        }

        $this->ajaxReturn($user);
    }

    public function updateUserJson()
    {
        $this->isLoginJson();

        $data = I("get.","","");
        D("User")->updateUser(session("userId"), $data);
    }

    public function getContactListJson()
    {
        $this->isLoginJson();

        $contact = D("Contact")->getContactList(array("user_id" => session("userId")));
        if (I("get.getProvince")) {
            $contact["province"] = D("LocProvince")->getProvinceList(array(), true);
        }

        $this->ajaxReturn($contact);
    }

    public function addContactJson()
    {
        $this->isLoginJson();

        D("Contact")->addContact(session("userId"), I("post."));
    }

    public function delContactJson()
    {
        $this->isLoginJson();

        D("Contact")->delContact(I("get.id"));
        $this->ajaxReturn(array("status" => "1"));
    }

    public function getFavoritesListJson()
    {
        $this->isLoginJson();

        $list = D("UserFavorites")->getFavoritesList(array("id" => session("userId")), true);
        $this->ajaxReturn($list);
    }

    public function addFavorites()
    {
        $this->isLoginJson();

        $data = array();
        $userFavorites = D("UserFavorites");
        if (strpos(I("get.product_id"), ',') != false) {
            $product_ids = explode(',', I("get.product_id"));
            foreach ($product_ids as $key => $value) {
                array_push($data, array("product_id" => $value, "user_id" => session("userId")));
            }
        } else {
            array_push($data, array("product_id" => I("get.product_id"), "user_id" => session("userId")));
        }

        foreach ($data as $key => $value) {
            $find = $userFavorites->getFavorites(array("user_id" => session("userId"), "product_id" => $value));
            if ($find) {
                unset($data[$key]);
            }
        }

        $userFavorites->addAllFavorites($data);
    }

    public function delFavorites()
    {
        $this->isLoginJson();

        D("UserFavorites")->delFavorites(I("get.product_id"), session("userId"));
    }

    public function logoutJson()
    {
        session(null);
        $this->ajaxReturn(array("info" => "注销成功", "status" => "1"));
    }
}